package org.jeecg.modules.yw.config;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.yw.service.EnterPriseService;
import org.jeecg.modules.yw.utils.DESUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

@Component
public class JWTInterceptor implements HandlerInterceptor {
	/**
     * 预处理回调方法，实现处理器预处理
     * 返回值：true表示继续流程；false表示流程中断，不会继续调用其他的拦截器或者处理器
     */
	@Resource
	private EnterPriseService enterpriseService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从http请求头key为Authorization中取出JWT
        String token = request.getHeader("token");
        try {
        	if (StringUtils.isNotBlank(token)) {
        		String id = DESUtil.decryptCBCId(token);
        		String timeStamp = DESUtil.decryptCBCRefreshToken(token);
        		String refreshToken = enterpriseService.getById(id).getRefreshToken();        		
        		if (!refreshToken.equals(timeStamp)) {
        			returnJson(response, "其他用户上线，您被迫下线!");
        			return false;
        		}        		
        	}  
            // ...          
        }catch (Exception e){
            returnJson(response,"token无效");
            e.printStackTrace();
        }
        return true;
    }
    
    /**
     * 返回格式化后的json到前端页面
     *
     * @param response
     * @param message
     * @throws Exception
     */
    private void returnJson(HttpServletResponse response, String message) throws Exception{
    	Result resultVo = new Result();
        PrintWriter writer = null;
         // 注意点1：这边返回配置为josn格式
        response.setContentType("application/json;charset=UTF-8");
        try {
        	 resultVo.setCode(501);
        	 resultVo.setMessage(message);
             writer = response.getWriter();
             // 注意点2，这样要用fastjson转换一下后，返回的前端才是格式化后的json格式
             writer.print(JSON.toJSONString(resultVo));
        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
